﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
using UtfprLibrary.EntityFramework.ComponentModel;
using UtfprLibrary.EntityFramework.Exceptions;

namespace UtfprLibrary.EntityFramework.Helpers {
    /// <summary>
    /// A static class used to help with UtfprDataSource logic
    /// </summary>
    public static class EntityDataSourceHelper {
        #region find/get

        /// <summary>
        /// Find the root UtfprBindingNavigator
        /// </summary>
        /// <param name="form">a Form which contains the root UtfprBindingNavigator used to start searching (with NavigatorSource property)</param>
        /// <returns>the root UtfprBindingNavigator</returns>
        public static IEntityDataSourceProvider findDataSource(Form form) {
            try {
                var flags = BindingFlags.NonPublic | BindingFlags.Instance;
                var allFields = new List<FieldInfo>();
                allFields.AddRange(form.GetType().GetFields(flags)); //inheritance
                allFields.AddRange(form.GetType().BaseType.GetFields(flags));//composition
                try {
                    var res = (from info in allFields
                               where typeof(IEntityDataSourceProvider).IsAssignableFrom(info.FieldType)
                               select info.GetValue(form) as IEntityDataSourceProvider)
                            .SingleOrDefault();
                    return res;
                } catch (NullReferenceException e) {
                    throw new ArgumentException("'IEntityDataSourceProvider' not found.", e);
                } 
            } catch (Exception ex) {
                throw new UtfprEFHelpersException("", ex);
            }
        }

        #endregion
    }
}